package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
)

var dbc orm.Ormer
var dbx *sqlx.DB

func init() {
	// 注册驱动
	orm.RegisterDriver("sqlite", orm.DRSqlite)
	// 注册默认数据库
	orm.RegisterDataBase("default", "sqlite3", "data.db")
	// 需要在init中注册定义的model
	orm.RegisterModel(new(User), new(Groups), new(Config), new(Friend))
	// 自动建表
	orm.RunSyncdb("default", false, true)

	dbc = orm.NewOrm()
	dbc.Using("default")

	//检测是否安装
	isInstall := dbc.Read(&Config{Option: "IsInstall", Value: "yes"}, "Option", "Value")
	if isInstall != nil {
		Initialization()
	}
	//sqlx
	dbx, _ = sqlx.Open("sqlite3", "data.db")
}

//安装初始化
func Initialization() {
	//配置表初始化
	dbc.Insert(&Config{Option: "IsInstall", Value: "yes"})
	dbc.Insert(&Config{Option: "WebTitle", Value: "GoIM"})
	dbc.Insert(&Config{Option: "CopyRight", Value: "GoIM"})
	//用户与群组表初始化
	dbc.Insert(&User{Username: "admin", Avatar: "/static/images/group.png", Password: "admin", Sign: "金鳞岂是池中物，一遇风雨便化龙"})
	dbc.Insert(&Groups{Name: "公共聊天室", Avatar: "/static/images/group.png"})
}
